package com.suneast.suneaststore.modules.personal.order.fragment;

import android.os.Bundle;
import android.support.annotation.LayoutRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.RadioButton;
import android.widget.TextView;

import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.suneast.suneaststore.R;
import com.suneast.suneaststore.bean.personal.order.ListBean;
import com.suneast.suneaststore.modules.common.Flag;
import com.suneast.suneaststore.modules.personal.order.OrderHandler;
import com.suneast.suneaststore.modules.personal.order.adapter.OrdersAdapter;
import com.suneast.suneaststore.modules.personal.order.event.ConfirmDeliverGoodsResult;
import com.suneast.suneaststore.modules.personal.order.event.DeliverConfirmedSucceed;
import com.suneast.suneaststore.modules.personal.order.event.ListResult;
import com.suneast.suneaststore.modules.shopcart.HandlePayFragment;
import com.suneast.suneaststore.ui.fragments.BaseFragment;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.BindViews;
import butterknife.OnClick;

@SuppressWarnings("unchecked")
public class SaleManage extends BaseFragment implements OrdersAdapter.OnOrderClickListener, OrdersAdapter.OrderButtonClickListener {
    private List<ListBean.Order>[] list = new ArrayList[]{
            new ArrayList<ListBean.Order>(), // ALL
            new ArrayList<ListBean.Order>(), // UNPAID
            new ArrayList<ListBean.Order>(), // TOBE_DELIVERED
            new ArrayList<ListBean.Order>(), // TOBE_RECEIVED
            new ArrayList<ListBean.Order>(), // TOBE_COMMENTED
            new ArrayList<ListBean.Order>()  // AFTER_SALES
    };

    private int[] pageIndexes = new int[6];

    @BindViews({R.id.rb_all_order, R.id.rb_unpaid, R.id.rb_tobe_delivered, R.id.rb_tobe_received, R.id.rb_tobe_commented, R.id.rb_after_sales})
    RadioButton[] radioButtons;
    private int orderChoice = 0;

    @BindView(R.id.title_bar)
    TextView title;
    @BindView(R.id.rv_order_list)
    RecyclerView rvOrderList;

    @BindView(R.id.srl_layout)
    SmartRefreshLayout srlLayout;
    @BindView(R.id.srlHeader)
    ClassicsHeader srlHeader;
    @BindView(R.id.srlFooter)
    ClassicsFooter srlFooter;

    private OrdersAdapter ordersAdapter;

    public SaleManage withId(int btn_id) {
        switch (btn_id) {
            case R.id.tv_merchant_all_order:
                orderChoice = 0;
                break;
            case R.id.tiv_merchant_goods_wait_pay:
                orderChoice = 1;
                break;
            case R.id.tiv_merchant_goods_wait_send:
                orderChoice = 2;
                break;
            case R.id.tiv_merchant_goods_arrived:
                orderChoice = 3;
                break;
            case R.id.tiv_merchant_goods_wait_appraise:
                orderChoice = 4;
                break;
        }
        return this;
    }

    @Override
    public @LayoutRes
    int setLayout() {
        return R.layout.fragment_order_manage;
    }

    @Override
    public void onBindView(@Nullable Bundle savedInstanceState, @NonNull View rootView) {
        title.setText(R.string.my_order);
        radioButtons[4].setText(R.string.order_done);
        rvOrderList.setNestedScrollingEnabled(false);
        rvOrderList.setLayoutManager(new LinearLayoutManager(getContext()));
        rvOrderList.addItemDecoration(new DividerItemDecoration(getContext(), DividerItemDecoration.VERTICAL));
        ordersAdapter = new OrdersAdapter(1);
        ordersAdapter.setOnOrderClickListener(this);
        ordersAdapter.setOrderButtonClickListener(this);
        rvOrderList.setAdapter(ordersAdapter);
        srlLayout.setEnableLoadMoreWhenContentNotFull(false);
        srlLayout.setOnRefreshListener(refreshLayout -> {
            list[orderChoice].clear();
            OrderHandler.requestSaleList(orderChoice, pageIndexes[orderChoice] = 0);
        });
        srlLayout.setOnLoadMoreListener(refreshLayout -> {
            srlFooter.setNoMoreData(false);
            OrderHandler.requestPurchaseList(orderChoice, pageIndexes[orderChoice]);
        });
        EventBus.getDefault().register(this);
        radioButtons[orderChoice].performClick();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onListResult(ListResult result) {
        int reqType = result.getType();
        if (result.getValue() == Flag.Result.SUCCEED) {
            if (result.getBean() != null) {
                list[reqType].addAll(result.getBean().getList());
                srlLayout.postDelayed(pageIndexes[reqType] == 0 ?
                        () -> srlLayout.finishRefresh(true) : () -> srlLayout.finishLoadMore(true), 500);
                ordersAdapter.setList(list[reqType]);
                pageIndexes[reqType]++;
            } else if (pageIndexes[reqType] == 0) {
                // 无数据 (走到这一般是出故障了)
                srlLayout.postDelayed(() -> srlLayout.finishRefresh(true), 500);
            } else {
                // 已全部加载 (走到这一般是出故障了)
                srlLayout.postDelayed(() -> srlLayout.finishLoadMore(true), 500);
            }
        } else {
            boolean flag = "没有数据".equals(result.getMsg());
            boolean pageFlag = pageIndexes[reqType] == 0;
            if (flag) { // 如是没有数据,page==0说明真的没有,否则就是已经加载到底了
                if (!pageFlag) {
                    srlFooter.setNoMoreData(true);
                }
            } else {
                ordersAdapter.setList(null);
            }
            srlLayout.postDelayed(pageFlag ?
                    () -> srlLayout.finishRefresh(flag) : () -> srlLayout.finishLoadMore(flag), 500);
        }
    }

    @OnClick(R.id.ib_return_back)
    void onBackPressed() {
        pop();
    }

    @OnClick({R.id.rb_all_order, R.id.rb_unpaid, R.id.rb_tobe_delivered, R.id.rb_tobe_received, R.id.rb_tobe_commented, R.id.rb_after_sales})
    void onViewClick(View view) {
        switch (view.getId()) {
            case R.id.rb_all_order:
                orderChoice = 0;
                break;
            case R.id.rb_unpaid:
                orderChoice = 1;
                break;
            case R.id.rb_tobe_delivered:
                orderChoice = 2;
                break;
            case R.id.rb_tobe_received:
                orderChoice = 3;
                break;
            case R.id.rb_tobe_commented:
                orderChoice = 4;
                break;
            case R.id.rb_after_sales:
                orderChoice = 5;
                break;
        }
        if (list[orderChoice].isEmpty()) {
            ordersAdapter.setList(null);
            OrderHandler.requestSaleList(orderChoice, pageIndexes[orderChoice]);
        } else {
            ordersAdapter.setList(list[orderChoice]);
        }
    }

    @Override
    public void onOrderClick(int orderId, int orderInfo) {
        switch (orderInfo & 0xff) { // orderType 0普通 1快速 2定制
            case 0:
                PurchaseOrderDetail fragment = new PurchaseOrderDetail();
                Bundle arguments = new Bundle();
                arguments.putInt(PurchaseOrderDetail.ORDER_ID, orderId);
                arguments.putInt(PurchaseOrderDetail.ORDER_ST, orderInfo >> 16);
                fragment.setArguments(arguments);
                start(fragment);
                break;
            case 1:
                start(new FastOrderDetail().withId(orderId));
                break;
            case 2:
                break;
        }
    }

    @Override
    public void onButtonClick(int orderId, int pos, int orderInfo, int btnId) {
        switch (orderInfo & 0xff) { // orderType 0普通 1快速 2定制
            case 0:
                if (btnId == R.id.btn_right) {//btn1
                    switch (orderInfo >> 16) {//根据订单状态来做不同的点击动作
                        case OrderHandler.ORDER_TOBE_DELIVERED: {
                            start(new ConfirmDeliveredFragment().withOrderId(orderId).withPos(pos));
                        }
                        break;
                        case OrderHandler.ORDER_CANCELED: {

                        }
                        break;
                        case OrderHandler.ORDER_UNPAID:
                            break;

                        case OrderHandler.ORDER_TOBE_RECEIVED:
                            break;
                        case OrderHandler.ORDER_TOBE_COMMENTED:

                            break;
                        case OrderHandler.ORDER_AFTER_SALES: // 据说这个不会出现，那就先空着

                            break;
                    }
                }
                break;
            case 1:
                if (btnId == R.id.btn_right) {
                    if (orderInfo >> 16 == OrderHandler.ORDER_TOBE_DELIVERED) {
                        start(new ConfirmDeliveredFragment().withOrderId(orderId).withPos(pos));
                    }
                }
                break;
            case 2:
                if (btnId == R.id.btn_left) {

                } else if (btnId == R.id.btn_right) {

                }
                break;
        }
    }

    private void removeItemThenUpdateRv(int pos) {
        ordersAdapter.getList().remove(pos);
        ordersAdapter.notifyItemRemoved(pos);
        if (pos != ordersAdapter.getList().size()) {
            ordersAdapter.notifyItemRangeChanged(pos, ordersAdapter.getList().size() - pos);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onSuccedConfirmDeliver(DeliverConfirmedSucceed event) {
        removeItemThenUpdateRv(event.getPos());
    }
}